/**
 * 
 */
package d.qapaper.tool;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;

/**
 * 处理表单类，用于获得指定区域内表单控件的值。
 * @author Kaven
 * 2011-5-24
 */
public class FormUtil {
	private View view;
	//定义分割符
	private final String splitString=" ";
	/**
	 * 
	 */
	public FormUtil(View view) {
		this.view=view;
	}
	
	/**
	 * 控件选择器
	 * @param field
	 * @return
	 */
	public  ArrayList<Object> ItemSelector(String field){
		String[] fields=this.getElItems(field);
		Class clazz=this.getItemType(field);
		Object object=(ReflectUtil.getObject(clazz));
		for (String el : fields) {
			object=view.findViewWithTag(field);
		}
		return null;
	}
	
	
	
	/**
	 * 解析指定区域控件的类型
	 * @param field
	 */
	private Class getItemType(String field){
		Class type=null;
		if (field.indexOf("#")==0) {
			String tag=field.substring(1);
			View view=this.view.findViewWithTag(tag);
			type=getItemTypeHandler(view);
		}
		return type;
	}
	
	/**
	 * 返回控件类型
	 * @param view
	 * @return
	 */
	private Class getItemTypeHandler(View view){
		Class type=null;
		//表单控件
		if(view instanceof Button){
			type=Button.class;
		}
		if(view instanceof TextView){
			type=TextView.class;
		}
		if(view instanceof EditText){
			type=EditText.class;
		}
		if(view instanceof ImageButton){
			type=ImageButton.class;
		}
		if(view instanceof CheckBox){
			type=CheckBox.class;
		}
		if(view instanceof RadioButton){
			type=RadioButton.class;
		}
		if(view instanceof RadioGroup){
			type=RadioGroup.class;
		}
		//布局
		if(view instanceof ScrollView){
			type=ScrollView.class;
		}
		if(view instanceof LinearLayout){
			type=LinearLayout.class;
		}
		if(view instanceof TableLayout){
			type=TableLayout.class;
		}
		if(view instanceof RelativeLayout){
			type=RelativeLayout.class;
		}
		if(view instanceof FrameLayout){
			type=FrameLayout.class;
		}
		return type;
	}
	
	
	/**
	 * 解析容器层级，类似jquery 选择器
	 * @return
	 */
	private String[] getElItems(String field){
		String[] fields=null;
		if(StringUtil.isEmpty(field)){
			Log.d("info", "FormUtil.getElItems参数为空。");
		}else {
			fields=field.split(splitString);
			if(!(fields.length>0)){
				Log.d("info", "FormUtil.getElItems不能正常分割，请检查字段之间的分隔。");
			}
		}
		return fields;
	}

}
